package com.concurrent.thread.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @author Mr.yuan
 * @version v1.0
 * @date 2019/9/26 17:24
 **/
@Component
public class MyExecutor {

    private static int maximumPoolSize = Runtime.getRuntime().availableProcessors()*2;

    private static ScheduledThreadPoolExecutor SCHEDULED_EXECUTOR;
    private static ThreadPoolExecutor EXECUTOR;
    private static final ThreadFactory FACTORY = new ThreadFactoryBuilder().setNameFormat("my-task-%d").build();

    @Bean("/myExecutor")
    public ThreadPoolExecutor initExecutor() {
        return buildExecutor();
    }
    @Bean("/myScheduledExecutor")
    public ScheduledThreadPoolExecutor initScheduledExecutor() {
        return buildScheduledExecutor();
    }

    public static synchronized ThreadPoolExecutor getExecutor(){
        if (null == EXECUTOR){
            return buildExecutor();
        }
        return EXECUTOR;
    }

    public static synchronized ScheduledThreadPoolExecutor getScheduledExecutor(){
        if (null == SCHEDULED_EXECUTOR){
            return buildScheduledExecutor();
        }
        return SCHEDULED_EXECUTOR;
    }

    private static ScheduledThreadPoolExecutor buildScheduledExecutor() {
        SCHEDULED_EXECUTOR =  new ScheduledThreadPoolExecutor(5, FACTORY);
        return SCHEDULED_EXECUTOR;
    }
    private static ThreadPoolExecutor buildExecutor() {
        EXECUTOR = new ThreadPoolExecutor(2, maximumPoolSize, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(200), FACTORY);
        return EXECUTOR;
    }
}
